'''
Author: thinktanker thinktanker@163.com
Date: 2024-08-13 15:18:35
LastEditors: thinktanker thinktanker@163.com
LastEditTime: 2024-08-15 09:18:33
FilePath: 
Description: 
'''
import subprocess
import asyncio
# IP 地址基础部分
BASE_IP = '10.32.157.'


async def ping_host(ip: str) -> bool:
    """异步执行 ping 命令并返回是否成功"""
    print(ip)
    result = True
    try:
        # 构建 ping 命令
        command = ["ping", "-n", "2", ip]

        # 使用 subprocess.create_subprocess_exec 异步执行 ping 命令
        process = await asyncio.create_subprocess_exec(*command,
                                                       stdout=subprocess.PIPE,
                                                       stderr=subprocess.PIPE)

        # 读取并输出标准输出
        while True:
            line = await process.stdout.readline()
            if not line:
                break
            line = line.decode(encoding='gbk', errors='ignore').strip()
            print(' ' * 10, end='\r')
            print(line, end='\r')
            if '无法访问目标主机' in line or '请求超时' in line:
                result = False
        # 等待命令完成
        await process.wait()
        # 检查返回码
        return result
    except Exception as e:
        print(f"Error pinging {ip}: {e}")
        return False


async def main():
    # IP 地址范围
    start = 10
    end = 250

    # 创建任务列表
    tasks = [
        asyncio.create_task(ping_host(f"{BASE_IP}{i}"))
        for i in range(start, end + 1)
    ]

    # 等待所有任务完成
    results = await asyncio.gather(*tasks)

    # 输出结果
    for i, is_up in enumerate(results, start=start):
        ip = f"{BASE_IP}{i}"
        if is_up:
            print(f"\033[32m{ip}\033[0m")
        # else:
        #     print(f"\033[31m{ip}\033[0m")


if __name__ == "__main__":
    asyncio.run(main())
    # ping()
'''
print("\033[31m这是红色字体\033[0m")
print("\033[32m这是绿色字体\033[0m")
print("\033[33m这是黄色字体\033[0m")
print("\033[34m这是蓝色字体\033[0m")
print("\033[38m这是默认字体\033[0m")  # 大于37将显示默认字体
'''
